import cv2
img = cv2.imread("cp.jpg",cv2.IMREAD_COLOR)
qzimg = cv2.GaussianBlur(img,(5,5),0.8,0.8)#高斯核大小 中心点为中心3 * 3的邻域做操作
gray_imag = cv2.cvtColor(qzimg,cv2.COLOR_RGB2GRAY)
#cv2.imshow("test",gray_imag
Sobel_x = cv2.Sobel(gray_imag,cv2.CV_64F,1,0)
absX = cv2.convertScaleAbs(Sobel_x)
image = absX
ret,image = cv2.threshold(image, 0, 255,cv2.THRESH_OTSU)
kernelX = cv2.getStructuringElement(cv2.MORPH_RECT, (17, 5))
image = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernelX, iterations=3)
kernelX = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 1))
kernelY = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 19))
image = cv2.dilate(image, kernelX)
image = cv2.erode(image, kernelX)
# 腐蚀膨胀
image = cv2.erode(image, kernelY)
image = cv2.dilate(image, kernelY)
image = cv2.medianBlur(image, 15)
cv2.RETR_EXTERNAL
# cv2.CHAIN_APPROX_SIMPLE压缩水平方向、垂直方向、对角线方向的元素，只保留该方向的终点坐标
contours, hierarchy = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
image_copy = img.copy()
cv2.drawContours(image_copy, contours, -1, (0, 255, 0), 2)
cv2.imshow("test",image_copy)
for item in contours:
    rect = cv2.boundingRect(item)
    x = rect[0]
    y = rect[1]
    weight = rect[2]
    height = rect[3]
    if (weight > (height * 3)) and (weight < (height * 4)):
        image = img[y:y + height, x:x + weight]
qzcp = cv2.GaussianBlur(image,(3,3),0)
gray_cpimg = cv2.cvtColor(qzcp,cv2.COLOR_RGB2GRAY)
ret,cpimages = cv2.threshold(gray_cpimg,0,255,cv2.THRESH_OTSU)
cv2.imshow("image_copy",cpimages)
cv2.waitKey(0)
